package com.cooldatasoft.util;

import java.lang.reflect.Method;
import java.util.Stack;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
/**
 * 
 * @author fatih mehmet ucar
 *
 */
public class LoggingInterceptor implements MethodBeforeAdvice,	AfterReturningAdvice, ThrowsAdvice {
	
	private static Log log = null;

	public LoggingInterceptor() {
	}

	
	Stack<Long> startTimeStack = new Stack<Long>();
	public void before(Method arg0, Object[] arg1, Object arg2)	throws Throwable {
		startTimeStack.push((Long) System.currentTimeMillis());
		log = LogFactory.getLog(arg2.getClass());
		log.debug("Beginning method: " + arg0.getName());
	}

	public void afterReturning(Object arg0, Method arg1, Object[] arg2,	Object arg3) throws Throwable {
		long time = System.currentTimeMillis()-startTimeStack.pop();
		log = LogFactory.getLog(arg3.getClass());
		log.debug("Ending method: " + arg1.getName());
		
		//FMU this section is executed by different threads overriding start value of the others
		//put start into a static stack? with thread id
		if(time>100){
			log.warn("Execution Time : "+time+"ms Class : "+arg3.getClass()+" Method : " + arg1.getName());
		}
	}

	public void afterThrowing(Method m, Object[] args, Object target, Throwable ex) {
		log = LogFactory.getLog(target.getClass());
		log.error("Exception in method: " + m.getName() + " Exception is: "+ ex.getMessage(),ex);
	}

	public static Log getLog() {
		return log;
	}

	
	
}